<?php
class Default_Service_Svc {
	protected $_customerId = null;
	protected $_token = null;
	protected $_key = null;
	protected $_auth = false;
	protected $_error = null;
	public function createProduct($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		$sku = ( string ) $paramter->ProductInfo->sku;
		
		$now = date ( 'Y-m-d H:i:s' );
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'sku' => $sku,
				'time' => $now 
		);
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		// $sku = (string)$paramter->ProductInfo->sku;
		$skuCNName = ( string ) $paramter->ProductInfo->skuCNName;
		$skuName = ( string ) $paramter->ProductInfo->skuName;
		$weight = ( float ) $paramter->ProductInfo->weight;
		$length = ( float ) $paramter->ProductInfo->length;
		$width = ( float ) $paramter->ProductInfo->width;
		$height = ( float ) $paramter->ProductInfo->height;
		$declareValue = ( float ) $paramter->ProductInfo->declareValue;
		$categoryId = ( int ) $paramter->ProductInfo->categoryId;
		$package = ( int ) $paramter->ProductInfo->package;
		$minQty = ( int ) $paramter->ProductInfo->minQty;
		if ($package == 0)
			$package = null;
		$image = $paramter->ProductInfo->image;
		$key = 0;
		if (count ( $image ) > 1) {
			foreach ( $image as $value ) {
				$skuImg [$key] = $value->imgUrl;
				$key ++;
			}
		} else {
			$skuImg [$key] = $image->imgUrl;
		}
		// qc options
		$productIsQc = 0; // 不需要QC
		$qcs = $paramter->ProductInfo->qcs;
		if (! isset ( $qcs )) {
			$qcs = array ();
		}
		$qcArr = array ();
		if (count ( $qcs )) {
			foreach ( $qcs as $v ) {
				$qcArr [] = array (
						'poc_id' => $v->pocId,
						'po_id' => '4',
						'po_value' => $v->poValue 
				);
			}
			$productIsQc = 1; // 需要QC
		}
		
		// $result['message'] = print_r($qcArr,true);
		// return $result;
		// 目录
		$productOptionValues [] = array (
				'poc_id' => $categoryId,
				'po_id' => '1' 
		);
		// 最小库存
		$productOptionValues [] = array (
				'poc_id' => $minQty,
				'po_id' => '3' 
		);
		
		$row = array (
				"product_title" => $skuName, // 产品名称
				"product_title_cn" => $skuCNName, // 产品中文名称
				"product_sku" => $sku, // 产品编号
				"product_weight" => $weight, // 产品重量
				"product_length" => $length, // 产品长
				"product_width" => $width, // 宽
				"product_height" => $height, // 高
				"product_declared_value" => $declareValue, // 申报价值
				"product_is_qc" => $productIsQc 
		); //
		
		$serviceObj = new Merchant_Service_Product ();
		$create = $serviceObj->create ( $row, $productOptionValues, null, $skuImg, $this->_customerId, $package, $qcArr );
		
		if ($create !== true) { // 创建失败
			$msg = null;
			foreach ( $create as $val ) {
				$msg .= $val . ';		';
			}
			$result ['message'] = $msg;
			return $result;
		}
		$result ['message'] = 'Success';
		$result ['ask'] = 'Success';
		return $result;
	}
	public function getProductBySKU($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		$sku = ( string ) $paramter->sku;
		$detailLevel = ( string ) $paramter->detailLevel;
		
		$now = date ( 'Y-m-d H:i:s' );
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'data' => '',
				'time' => $now 
		);
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		$pObj = new Merchant_Service_Product ();
		$productInfo = $pObj->getProductBySku ( $sku, $this->_customerId );
		
		if (! $detailLevel)
			$detailLevel = 0;
		if ($detailLevel == '0') {
			$data = array (
					'sku' => $productInfo ['product_sku'],
					'productTitle' => $productInfo ['product_title'],
					'productAddTime' => $productInfo ['product_date_added'],
					'productLastModified' => $productInfo ['product_last_modified'],
					'productStatu' => $productInfo ['product_status'] 
			);
		} else {
			$stock = Merchant_Service_WarehouseProducts::getStockByProduct ( $productInfo ['product_id'] );
			$totalStock = 0;
			$totalStockHold = 0;
			foreach ( $stock as $key => $val ) {
				$warehouseInfo = array (
						'warehouse' => $val ['warehouse'],
						'stock' => $val ['stock'],
						'stockOnHold' => $val ['stockOnHold'] 
				);
				$totalStock += $val ['stock'];
				$totalStockHold += $val ['stockOnHold'];
			}
			
			$data = array (
					'sku' => $productInfo ['product_sku'],
					'productTitle' => $productInfo ['product_title'],
					'productTitleCn' => $productInfo ['product_title_cn'],
					'productAddTime' => $productInfo ['product_date_added'],
					'productLastModified' => $productInfo ['product_last_modified'],
					'productStatu' => $productInfo ['product_status'],
					'productLength' => $productInfo ['product_length'],
					'productWidth' => $productInfo ['product_width'],
					'productHeight' => $productInfo ['product_height'],
					'productWeight' => $productInfo ['product_weight'],
					'declaredValue' => $productInfo ['product_declared_value'],
					'categoryId' => $productInfo ['category'] ['poc_id'],
					'category' => $productInfo ['category'] ['poc_value'],
					'warehouseInfo' => $warehouseInfo,
					'warehouseStock' => $totalStock,
					'warehouseStockOnHold' => $totalStockHold 
			);
		}
		$result ['ask'] = 'Success';
		$result ['data'] = $data;
		return $result;
	}
	
	/*
	 * createASN
	 */
	public function createASN($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		
		$now = date ( 'Y-m-d H:i:s' );
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'ASNCode' => '',
				'time' => $now 
		);
		
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		
		$receivingArr ['ref_id'] = ( string ) $paramter->ASNInfo->referenceNo;
		$receivingArr ['description'] = ( string ) $paramter->ASNInfo->instructions;
		$receivingArr ['customer_id'] = $this->_customerId;
		$receivingArr ['warehouse_id'] = 1; // 只有一个仓库，ID为 1
		$receivingArr ['order_type'] = 1; // 默认为 1 ，标准
		$receivingArr ['status'] = 1;
		$receivingArr ['created'] = $now;
		$receivingArr ['pickup'] = 0; // 暂时默认为0
		$receivingArr ['supplier_id'] = '';
		
		$orderDetail = $paramter->ASNInfo->ASNDetail;
		
		$key = 0;
		$orderProduct = array ();
		$chkArr = array (); // qc
		$priorityArr = array (); // 优先级
		$productObj = new Merchant_Service_Product ();
		if (count ( $orderDetail ) > 1) {
			foreach ( $orderDetail as $value ) {
				if ($value->sku) {
					if (! isset ( $value->isQC )) { // 默认值
						$value->isQC = 0;
					}
					if (! isset ( $value->priorityLevel )) { // 默认值
						$value->priorityLevel = 0;
					}
					$product = $productObj->getProductBySku ( $value->sku, $this->_customerId );
					if (! $product) {
						$result ['message'] = 'SKU: ' . $value->sku . '  can not found.';
						return $result;
					}
					
					$isQC = $value->isQC;
					if (! $value->isQC) {
						$isQC = $product ['product_is_qc'] ? 1 : 0;
					}
					
					if ($isQC) {
						$pocArr = Merchant_Service_ProductOptionValue::getByProductId ( $product ['product_id'], 4 );
						if (count ( $pocArr ) == 0) {
							$result ['message'] = 'product_id:' . $product ['product_id'] . ' qc items is null.';
							return $result;
						}
					}
					
					$chkArr += array (
							"{$product['product_id']}" => $isQC 
					);
					$priority = 0;
					if ($value->priorityLevel) {
						$priority = $value->priorityLevel;
					}
					$priorityArr += array (
							"{$product['product_id']}" => $priority 
					);
					
					$tmp = array (
							"{$product['product_id']}" => $value->quantity 
					);
					
					$orderProduct += $tmp; // array_merge($orderProduct,);
				} else {
					$result ['message'] = 'SKU can not be null.';
					return $result;
				}
				$key ++;
			}
		} elseif (count ( $orderDetail ) == 1) {
			if ($orderDetail->sku) {
				if (! isset ( $orderDetail->isQC )) { // 默认值
					$orderDetail->isQC = 0;
				}
				if (! isset ( $value->priorityLevel )) { // 默认值
					$value->priorityLevel = 0;
				}
				$product = $productObj->getProductBySku ( $orderDetail->sku, $this->_customerId );
				if (! $product) {
					$result ['message'] = 'SKU: ' . $value->sku . '  can not found.';
					return $result;
				}
				$isQC = $orderDetail->isQC;
				if (! $orderDetail->isQC) {
					$isQC = $product ['product_is_qc'] ? 1 : 0;
				}
				
				if ($isQC) {
					$pocArr = Merchant_Service_ProductOptionValue::getByProductId ( $product ['product_id'], 4 );
					if (empty ( $pocArr )) {
						$result ['message'] = 'product_id:' . $product ['product_id'] . ' qc items is null...';
						return $result;
					}
				}
				
				$chkArr = array (
						"{$product['product_id']}" => $isQC 
				); // qc
				$priority = 0;
				if ($orderDetail->priorityLevel) {
					$priority = $value->priorityLevel;
				}
				$priorityArr += array (
						"{$product['product_id']}" => $priority 
				); // priority
				
				$orderProduct = array (
						"{$product['product_id']}" => $orderDetail->quantity 
				);
			} else {
				$result ['message'] = 'SKU can not be null.';
				return $result;
			}
		} else {
			$result ['message'] = 'Order Detail can not be null.';
			return $result;
		}
		
		$asnObj = new Merchant_Service_AsnProccess ();
		$return = $asnObj->create ( $orderProduct, $receivingArr, $this->_customerId, $chkArr, $priorityArr );
		
		if ($return ['ask'] != 'Success' || ! $return ['ask']) {
			$result ['ask'] = 'Error';
			$result ['message'] = $return ['msg'];
			return $result;
		}
		$result ['ask'] = 'Success';
		$result ['ASNCode'] = $return ['receiving_code'];
		$result ['message'] = $return ['msg'];
		return $result;
	}
	
	/*
	 * getAsnInfo
	 */
	public function getAsnInfo($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		$AsnCode = ( string ) $paramter->AsnCode;
		$detailLevel = ( string ) $paramter->detailLevel;
		
		$now = date ( 'Y-m-d H:i:s' );
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'data' => '',
				'time' => $now 
		);
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		$pObj = new Merchant_Service_AsnProccess ();
		$asnInfo = $pObj->getAsnInfo ( $AsnCode, $this->_customerId );
		
		if (! $asnInfo) {
			$result ['message'] = 'Asn Code not found!';
		}
		
		$result ['ask'] = 'Success';
		$result ['data'] = $asnInfo;
		return $result;
	}
	
	/*
	 * deleteAsn
	 */
	public function updateAsnStatus($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		$AsnCode = ( string ) $paramter->AsnCode;
		$AsnStatus = ( string ) $paramter->AsnStatus;
		
		$now = date ( 'Y-m-d H:i:s' );
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'time' => $now 
		);
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		$pObj = new Merchant_Service_AsnProccess ();
		$asnInfo = $pObj->getAsnInfo ( $AsnCode, $this->_customerId );
		
		if (! $asnInfo) {
			$result ['message'] = 'Asn Code not found!';
			return $result;
		}
		
		$result ['AsnCode'] = $asnInfo ['AsnCode'];
		if ($AsnStatus == $asnInfo ['AsnStatu']) {
			$result ['message'] = 'Asn status is same!';
			return $result;
		}
		if (! in_array ( $AsnStatus, array (
				"0",
				"1" 
		) ) || ! in_array ( $asnInfo ['AsnStatu'], array (
				"0",
				"1" 
		) )) {
			$result ['message'] = 'forbidden update,Asn is in operation!';
			return $result;
		}
		
		if ($AsnStatus == "1" && empty ( $asnInfo ['AsnDetail'] )) { // 变为确定状态
		                                                             // 需要验证
			$result ['message'] = 'asn item empty!';
			return $result;
		}
		$Obj = new Merchant_Model_Receiving ();
		// 将状态更新
		if (! $Obj->update ( array (
				'status' => $AsnStatus 
		), $asnInfo ['AsnCode'], "receiving_code" )) {
			$result ['message'] = 'Asn  delete fail';
		} else {
			$result ['ask'] = 'Success';
		}
		
		return $result;
	}
	/*
	 * updateProduct
	 */
	public function updateProductStatu($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		$sku = ( string ) $paramter->sku;
		$statu = ( string ) $paramter->statu;
		$now = date ( 'Y-m-d H:i:s' );
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'sku' => $sku,
				'time' => $now 
		);
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		// :0删除,1已激活,2草稿
		$statArr = array (
				0,
				1,
				2 
		);
		
		$productObj = new Merchant_Service_Product ();
		$productInfo = $productObj->getProductBySku ( $sku, $this->_customerId );
		
		if (! $productInfo || empty ( $productInfo )) {
			$result ['message'] = 'SKU:"' . $sku . '", Doesn\'t exist. ';
			return $result;
		}
		if (! in_array ( $statu, $statArr )) {
			$result ['message'] = 'product statu is not allow. ';
			return $result;
		}
		$pProc = new Merchant_Service_ProductProccess ( $productInfo ['product_id'], $this->_customerId );
		$return = $pProc->submited ( $statu );
		
		if ($return ['ask'] == 'Error') {
			
			$result ['message'] = $return ['msg'];
			return $result;
		}
		$result ['message'] = 'Success';
		$result ['ask'] = 'Success';
		return $result;
	}
	/*
	 * add orders
	 */
	public function createOrder($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		
		$now = date ( 'Y-m-d H:i:s' );
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'orderCode' => '',
				'time' => $now 
		);
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		$referenceNo = ( string ) $paramter->orderInfo->referenceNo;
		$consigneeFirstName = ( string ) $paramter->orderInfo->consigneeFirstName;
		$consigneeLastName = ( string ) $paramter->orderInfo->consigneeLastName;
		$consigneeCompany = ( string ) $paramter->orderInfo->consigneeCompany;
		$consigneeCountry = ( string ) $paramter->orderInfo->consigneeCountry;
		$shippingMethodCode = ( string ) $paramter->orderInfo->shippingMethodCode;
		$consigneeZip = ( string ) $paramter->orderInfo->consigneeZip;
		$consigneeState = ( string ) $paramter->orderInfo->consigneeState;
		$consigneeCity = ( string ) $paramter->orderInfo->consigneeCity;
		$consigneeAddress1 = ( string ) $paramter->orderInfo->consigneeAddress1;
		$consigneeAddress2 = ( string ) $paramter->orderInfo->consigneeAddress2;
		$consigneePhone = ( string ) $paramter->orderInfo->consigneePhone;
		
		$consigneeEmail = ( string ) $paramter->orderInfo->consigneeEmail;
		$instructions = ( string ) $paramter->orderInfo->instructions;
		$orderStatu = ( int ) $paramter->orderInfo->orderStatu;
		
		// Order detail
		$orderDetail = $paramter->orderInfo->orderDetail;
		$countryObj = new Default_Service_Country ();
		$countryId = $countryObj->getIdByName ( $consigneeCountry );
		if (! $countryId) {
			$result ['message'] = 'Can not find this country.';
			return $result;
		}
		
		$key = 0;
		$productObj = new Merchant_Service_Product ();
		$parcelContents = '';
		$declaredValue = 0;
		$parcelQty = 0;
		$weight = 0;
		
		if (count ( $orderDetail ) > 1) {
			foreach ( $orderDetail as $value ) {
				if ($value->sku) {
					$product = $productObj->getProductBySku ( $value->sku, $this->_customerId );
					
					if (! $product) {
						$result ['message'] = 'SKU: ' . $value->sku . '  can not be found.';
						return $result;
					}
					$op_category = 0;
					$cagetory = $productObj->getProductCategory ( $product ['product_id'] );
					if ($cagetory) {
						$op_category = $cagetory ['poc_id'];
					}
					$orderProduct [] = array (
							'product_id' => $product ['product_id'],
							'op_quantity' => $value->quantity,
							'product_sku' => $product ['product_sku'],
							'op_description' => $product ['product_title'],
							'op_unit_price' => $product ['product_declared_value'],
							'op_subtotal' => round ( $product ['product_declared_value'] * $value->quantity, 2 ),
							'op_declared_value' => round ( $product ['product_declared_value'] * $value->quantity, 2 ),
							'op_weight' => round ( $product ['product_weight'] * $value->quantity, 4 ),
							'op_category' => $op_category 
					);
					$weight += round ( $product ['product_weight'] * $value->quantity, 4 );
					$declaredValue += round ( $product ['product_declared_value'] * $value->quantity, 2 );
					$parcelContents .= $product ['product_title'] . ';	';
					$parcelQty += $value->quantity;
				} else {
					$result ['message'] = 'SKU can not be null.';
					return $result;
				}
				$key ++;
			}
		} else {
			if ($orderDetail->sku) {
				$product = $productObj->getProductBySku ( $orderDetail->sku, $this->_customerId );
				if (! $product) {
					$result ['message'] = 'SKU: ' . $orderDetail->sku . '  can not be found.';
					return $result;
				}
				$op_category = 0;
				$cagetory = $productObj->getProductCategory ( $product ['product_id'] );
				if ($cagetory) {
					$op_category = $cagetory ['poc_id'];
				}
				$orderProduct [] = array (
						'product_id' => $product ['product_id'],
						'op_quantity' => $orderDetail->quantity,
						'product_sku' => $product ['product_sku'],
						'op_description' => $product ['product_title'],
						'op_unit_price' => $product ['product_declared_value'],
						'op_subtotal' => round ( $product ['product_declared_value'] * $orderDetail->quantity, 2 ),
						'op_declared_value' => round ( $product ['product_declared_value'] * $orderDetail->quantity, 2 ),
						'op_weight' => round ( $product ['product_weight'] * $orderDetail->quantity, 4 ),
						'op_category' => $op_category 
				);
				$weight += round ( $product ['product_weight'] * $orderDetail->quantity, 4 );
				$declaredValue += round ( $product ['product_declared_value'] * $orderDetail->quantity, 2 );
				$parcelContents .= $product ['product_title'];
				$parcelQty += $orderDetail->quantity;
			} else {
				$result ['message'] = 'SKU can not be null.';
				return $result;
			}
		}
		$shipMethod = Default_Service_ShipType::getByValue ( $shippingMethodCode, $field = 'st_code' );
		if (! $shipMethod || $shipMethod ['st_status'] != '1') {
			$result ['message'] = 'Shipping method is not Available.';
			return $result;
		}
		$options = array (
				'warehouseId' => 1,
				'countryId' => $countryId,
				'stId' => $shipMethod ['st_id'],
				'weight' => $weight,
				'length' => 1,
				'width' => 1,
				'height' => 1,
				'customerId' => $this->_customerId 
		);
		$shipFeeObj = new Default_Service_ShipFeeCalc ( $options );
		$fee = $shipFeeObj->calcFeeByType ();
		if (! is_array ( $fee )) {
			$result ['message'] = $fee;
			return $result;
		}
		
		$orderInfo = array (
				'customer_id' => $this->_customerId,
				'consignee_address1' => $consigneeAddress1,
				'consignee_address2' => $consigneeAddress2,
				'consignee_city' => $consigneeCity,
				'consignee_company' => $consigneeCompany,
				'consignee_country_id' => $countryId,
				'consignee_email' => $consigneeEmail,
				'consignee_first_name' => $consigneeFirstName,
				'consignee_last_name' => $consigneeLastName,
				'consignee_phone' => $consigneePhone,
				'consignee_region' => $consigneeState,
				'consignee_zip' => $consigneeZip,
				'customer_order_code' => $referenceNo,
				'parcel_contents' => $parcelContents,
				'parcel_declared_value' => $declaredValue,
				'parcel_quantity' => $parcelQty,
				'remark' => $instructions,
				'shipping_method' => $shippingMethodCode,
				'order_product' => $orderProduct,
				'shipping_fee_estimate' => $fee ['inter_fee'] 
		);
		// 去除前后空格
		foreach ( $orderInfo as $k => $v ) {
			if (! is_array ( $v )) {
				$orderInfo [$k] = trim ( $v );
			}
		}
		
		$return = Merchant_Service_OrderProccess::addOrder ( $orderInfo );
		
		// return $return;
		if ($return ['ask'] == false) {
			$result ['message'] = join ( '; ', $return ['list'] ['error'] );
			return $result;
		}
		if (! $orderStatu)
			$orderStatu = 1;
		$orderCode = $return ['ordersCode'];
		$arrStat = array (
				'0',
				'1',
				'2',
				'3' 
		);
		if (! in_array ( $orderStatu, $arrStat )) {
			$result ['message'] = 'Order status Can not be modify.';
			return $result;
		}
		if ($orderStatu > '1') { // 交寄订单
			$orderPocc = new Merchant_Service_OrderProccess ( $orderCode );
			$orderPocc->setCustomer ( $this->_customerId );
			$opStat = $orderPocc->submited ( $orderCode = null, $orderStatu );
			if ($opStat ['ask'] != 'Success') {
				$result ['ask'] = 'SuccessWithWarning';
				$result ['orderCode'] = $orderCode;
				$result ['message'] = 'Warning, change orders status failure, ' . $opStat ['msg'];
				return $result;
			}
		}
		
		$result ['ask'] = 'Success';
		$result ['message'] = 'Successful';
		$result ['orderCode'] = $orderCode;
		
		return $result;
	}
	
	/*
	 * add orders
	 */
	public function createEspecialOrder($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		
		$now = date ( 'Y-m-d H:i:s' );
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'orderCode' => '',
				'time' => $now 
		);
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		
		$referenceNo = ( string ) $paramter->orderInfo->referenceNo;
		$consigneeFirstName = ( string ) $paramter->orderInfo->consigneeFirstName;
		$consigneeLastName = ( string ) $paramter->orderInfo->consigneeLastName;
		$consigneeCompany = ( string ) $paramter->orderInfo->consigneeCompany;
		$consigneeCountry = ( string ) $paramter->orderInfo->consigneeCountry;
		$shippingMethodCode = ( string ) $paramter->orderInfo->shippingMethodCode;
		$consigneeZip = ( string ) $paramter->orderInfo->consigneeZip;
		$consigneeState = ( string ) $paramter->orderInfo->consigneeState;
		$consigneeCity = ( string ) $paramter->orderInfo->consigneeCity;
		$consigneeAddress1 = ( string ) $paramter->orderInfo->consigneeAddress1;
		$consigneeAddress2 = ( string ) $paramter->orderInfo->consigneeAddress2;
		$consigneePhone = ( string ) $paramter->orderInfo->consigneePhone;
		
		$consigneeEmail = ( string ) $paramter->orderInfo->consigneeEmail;
		$instructions = ( string ) $paramter->orderInfo->instructions;
		$orderStatu = ( int ) $paramter->orderInfo->orderStatu;
		
		// Order detail
		$orderDetail = $paramter->orderInfo->orderDetail;
		$countryObj = new Default_Service_Country ();
		$countryId = $countryObj->getIdByName ( $consigneeCountry );
		if (! $countryId) {
			$result ['message'] = 'Can not find this country.';
			return $result;
		}
		
		$regAccType = ( string ) $paramter->orderInfo->regAccType;
		$regAccount = ( string ) $paramter->orderInfo->regAccount;
		
		switch (strtolower ( $regAccType )) {
			case 'ebay' :
				$regAccType = 'ebay';
				break;
			case 'amazon' :
				$regAccType = 'amazon';
				break;
			default :
				$regAccType = 'other';
				break;
		}
		
		$regArr = array (
				'ori_account_type' => $regAccType,
				'ori_ref_account' => $regAccount 
		);
		
		$key = 0;
		$productObj = new Merchant_Service_Product ();
		$parcelContents = '';
		$declaredValue = 0;
		$parcelQty = 0;
		$weight = 0;
		
		if (count ( $orderDetail ) > 1) {
			foreach ( $orderDetail as $value ) {
				if ($value->sku) {
					$product = $productObj->getProductBySku ( $value->sku, $this->_customerId );
					
					if (! $product) {
						$result ['message'] = 'SKU: ' . $value->sku . '  can not be found.';
						return $result;
					}
					$opCategory = 0;
					$cagetory = $productObj->getProductCategory ( $product ['product_id'] );
					if ($cagetory) {
						$opCategory = $cagetory ['poc_id'];
					}
					$orderProduct [] = array (
							'product_id' => $product ['product_id'],
							'op_quantity' => $value->quantity,
							'product_sku' => $product ['product_sku'],
							'op_description' => $value->refTitle ? $value->refTitle : $product ['product_title'],
							'op_unit_price' => $product ['product_declared_value'],
							'op_subtotal' => round ( $product ['product_declared_value'] * $value->quantity, 2 ),
							'op_declared_value' => $value->refWorth ? $value->refWorth : round ( $product ['product_declared_value'] * $value->quantity, 2 ),
							'op_weight' => round ( $product ['product_weight'] * $value->quantity, 4 ),
							'op_ref_tnx' => $value->refTxnId ? $value->refTxnId : 0,
							'op_ref_item_id' => $value->refItemId,
							'op_ref_paydate' => $value->refPayDate,
							'op_category' => $opCategory 
					);
					
					$weight += round ( $product ['product_weight'] * $value->quantity, 4 );
					$declaredValue += round ( $product ['product_declared_value'] * $value->quantity, 2 );
					$parcelContents .= $product ['product_title'] . ';	';
					$parcelQty += $value->quantity;
				} else {
					$result ['message'] = 'SKU can not be null.';
					return $result;
				}
				$key ++;
			}
		} else {
			if ($orderDetail->sku) {
				$product = $productObj->getProductBySku ( $orderDetail->sku, $this->_customerId );
				if (! $product) {
					$result ['message'] = 'SKU: ' . $orderDetail->sku . '  can not be found.';
					return $result;
				}
				$opCategory = 0;
				$cagetory = $productObj->getProductCategory ( $product ['product_id'] );
				if ($cagetory) {
					$opCategory = $cagetory ['poc_id'];
				}
				$orderProduct [] = array (
						'product_id' => $product ['product_id'],
						'op_quantity' => $orderDetail->quantity,
						'product_sku' => $product ['product_sku'],
						'op_description' => $orderDetail->refTitle ? $orderDetail->refTitle : $product ['product_title'],
						'op_unit_price' => $product ['product_declared_value'],
						'op_subtotal' => round ( $product ['product_declared_value'] * $orderDetail->quantity, 2 ),
						'op_declared_value' => $orderDetail->refWorth ? $orderDetail->refWorth : round ( $product ['product_declared_value'] * $orderDetail->quantity, 2 ),
						'op_weight' => round ( $product ['product_weight'] * $orderDetail->quantity, 4 ),
						'op_ref_tnx' => $orderDetail->refTxnId ? $orderDetail->refTxnId : 0,
						'op_ref_item_id' => $orderDetail->refItemId,
						'op_ref_paydate' => $orderDetail->refPayDate,
						'op_category' => $opCategory 
				);
				$weight += round ( $product ['product_weight'] * $orderDetail->quantity, 4 );
				$declaredValue += round ( $product ['product_declared_value'] * $orderDetail->quantity, 2 );
				$parcelContents .= $product ['product_title'];
				$parcelQty += $orderDetail->quantity;
			} else {
				$result ['message'] = 'SKU can not be null.';
				return $result;
			}
		}
		
		$shipMethod = Default_Service_ShipType::getByValue ( $shippingMethodCode, $field = 'st_code' );
		
		if (! $shipMethod || $shipMethod ['st_status'] != '1') {
			$result ['message'] = 'Shipping method is not Available.';
			return $result;
		}
		
		$options = array (
				'warehouseId' => 1,
				'countryId' => $countryId,
				'stId' => $shipMethod ['st_id'],
				'weight' => $weight,
				'length' => 1,
				'width' => 1,
				'height' => 1,
				'customerId' => $this->_customerId 
		);
		$shipFeeObj = new Default_Service_ShipFeeCalc ( $options );
		$fee = $shipFeeObj->calcFeeByType ();
		if (! is_array ( $fee )) {
			$result ['message'] = $fee;
			return $result;
		}
		$orderInfo = array (
				'customer_id' => $this->_customerId,
				'consignee_address1' => $consigneeAddress1,
				'consignee_address2' => $consigneeAddress2,
				'consignee_city' => $consigneeCity,
				'consignee_company' => $consigneeCompany,
				'consignee_country_id' => $countryId,
				'consignee_email' => $consigneeEmail,
				'consignee_first_name' => $consigneeFirstName,
				'consignee_last_name' => $consigneeLastName,
				'consignee_phone' => $consigneePhone,
				'consignee_region' => $consigneeState,
				'consignee_zip' => $consigneeZip,
				'customer_order_code' => $referenceNo,
				'parcel_contents' => $parcelContents,
				'parcel_declared_value' => $declaredValue,
				'parcel_quantity' => $parcelQty,
				'remark' => $instructions,
				'shipping_method' => $shippingMethodCode,
				'order_product' => $orderProduct,
				'shipping_fee_estimate' => $fee ['inter_fee'],
				'regAccount' => $regArr 
		);
		
		$return = Merchant_Service_OrderProccess::addOrder ( $orderInfo );
		
		if ($return ['ask'] == false) {
			$result ['message'] = join ( '; ', $return ['list'] ['error'] );
			return $result;
		}
		if (! $orderStatu)
			$orderStatu = 1;
		$orderCode = $return ['ordersCode'];
		
		$arrStat = array (
				'0',
				'1',
				'2',
				'3' 
		);
		if (! in_array ( $orderStatu, $arrStat )) {
			$result ['message'] = 'Order status Can not be modify.';
			return $result;
		}
		if ($orderStatu > '1') { // 交寄订单
			$orderPocc = new Merchant_Service_OrderProccess ( $orderCode );
			$orderPocc->setCustomer ( $this->_customerId );
			$opStat = $orderPocc->submited ( $orderCode, $orderStatu );
			
			if ($opStat ['ask'] != 'Success') {
				$result ['ask'] = 'SuccessWithWarning';
				$result ['orderCode'] = $orderCode;
				$result ['message'] = 'Warning, change orders status failure, ' . $opStat ['msg'];
				return $result;
			}
		}
		
		$result ['ask'] = 'Success';
		$result ['message'] = 'Successful';
		$result ['orderCode'] = $orderCode;
		
		return $result;
	}
	
	/*
	 * getCountry
	 */
	public function getCountry($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		
		$now = date ( 'Y-m-d H:i:s' );
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'data' => '',
				'time' => $now 
		);
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		$country = Default_Service_Country::getAll ();
		
		foreach ( $country as $val ) {
			$arr ['countries'] [] = $val ['en_name'];
		}
		$result ['ask'] = 'Success';
		$result ['message'] = 'Success.';
		$result ['data'] = $arr;
		return $result;
	}
	/*
	 * getShippingMethod
	 */
	public function getShippingMethod($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		
		$now = date ( 'Y-m-d H:i:s' );
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'data' => '',
				'time' => $now 
		);
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		
		$shipTypeObj = new Default_Model_ShipType ();
		$condition ['st_status'] = 1;
		$shipType = $shipTypeObj->getByCondition ( $condition );
		
		foreach ( $shipType as $key => $val ) {
			$arr [$key] ['serviceCode'] = $val ['st_code'];
			$arr [$key] ['enName'] = $val ['st_name'];
			$arr [$key] ['cnName'] = $val ['st_name_cn'];
			$arr [$key] ['deliveryTimeMin'] = $val ['st_delivery_time_min'];
			$arr [$key] ['deliveryTimeMax'] = $val ['st_delivery_time_max'];
		}
		
		$result ['ask'] = 'Success';
		$result ['message'] = 'Success.';
		$result ['data'] = $arr;
		return $result;
	}
	
	/*
	 * updateOrder
	 */
	public function updateOrder($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		$ordersCode = ( string ) $paramter->ordersCode;
		$now = date ( 'Y-m-d H:i:s' );
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'ordersCode' => $ordersCode,
				'time' => $now 
		);
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		
		if (! $ordersCode) {
			$result ['message'] = 'Order code can not be null.';
			return $result;
		}
		$orders = Merchant_Service_Orders::getByValue ( $ordersCode, $field = 'orders_code' );
		if (! $orders || empty ( $orders )) {
			$result ['message'] = 'Can not find this order. Order Code:' . $ordersCode;
			return $result;
		} elseif ($orders->customer_id != $this->_customerId) {
			$result ['message'] = 'No permissions.';
			return $result;
		}
		
		$arrStat = array (
				'0',
				'1',
				'2',
				'3' 
		);
		if (! in_array ( $orders->orders_status, $arrStat )) {
			$result ['message'] = 'Order status Can not be modify.';
			return $result;
		}
		$consigneeCountry = ( string ) $paramter->ProductInfo->consigneeCountry;
		
		// update consignee country
		if ($consigneeCountry) {
			$countryObj = new Default_Service_Country ();
			$countryId = $countryObj->getIdByName ( $consigneeCountry );
			if (! $countryId) {
				$result ['message'] = 'Can not find this country.';
				return $result;
			} else {
				$countryId = $orders->consignee_country_id;
			}
		}
		
		$referenceNo = $paramter->orderInfo->referenceNo ? $paramter->orderInfo->referenceNo : $orders->customer_order_code;
		$consigneeFirstName = $paramter->orderInfo->consigneeFirstName ? $paramter->orderInfo->consigneeFirstName : $orders->consignee_first_name;
		$consigneeLastName = $paramter->orderInfo->consigneeLastName ? $paramter->orderInfo->consigneeLastName : $orders->consignee_last_name;
		$consigneeCompany = $paramter->orderInfo->consigneeCompany ? $paramter->orderInfo->consigneeCompany : $orders->consignee_company;
		$shippingMethodCode = $paramter->orderInfo->shippingMethodCode ? $paramter->orderInfo->shippingMethodCode : $orders->shipping_method;
		$consigneeZip = $paramter->orderInfo->consigneeZip ? $paramter->orderInfo->consigneeZip : $orders->consignee_zip;
		$consigneeState = $paramter->orderInfo->consigneeState ? $paramter->orderInfo->consigneeState : $orders->consignee_region;
		$consigneeCity = $paramter->orderInfo->consigneeCity ? $paramter->orderInfo->consigneeCity : $orders->consignee_city;
		$consigneeAddress1 = $paramter->orderInfo->consigneeAddress1 ? $paramter->orderInfo->consigneeAddress1 : $orders->consignee_address1;
		$consigneeAddress2 = $paramter->orderInfo->consigneeAddress2 ? $paramter->orderInfo->consigneeAddress2 : $orders->consignee_address2;
		$consigneePhone = $paramter->orderInfo->consigneePhone ? $paramter->orderInfo->consigneePhone : $orders->consignee_phone;
		
		$consigneeEmail = $paramter->orderInfo->consigneeEmail ? $paramter->orderInfo->consigneeEmail : $orders->consignee_email;
		$instructions = $paramter->orderInfo->instructions ? $paramter->orderInfo->instructions : $orders->remark;
		$orderStatu = $paramter->orderInfo->orderStatu ? $paramter->orderInfo->orderStatu : $orders->orders_status;
		
		// Order detail
		$orderDetail = $paramter->orderInfo->orderDetail;
		$key = 0;
		$productObj = new Merchant_Service_Product ();
		$parcelContents = '';
		$declaredValue = 0;
		$parcelQty = 0;
		
		if (count ( $orderDetail ) > 1) {
			foreach ( $orderDetail as $value ) {
				if ($value->sku) {
					$product = $productObj->getProductBySku ( $value->sku );
					if (! $product) {
						$result ['message'] = 'SKU: ' . $value->sku . '  can not be found.';
						return $result;
					}
					$orderProduct [] = array (
							'product_id' => $product ['product_id'],
							'op_quantity' => $value->quantity,
							'product_sku' => $product ['product_sku'],
							'op_description' => $product ['product_title'],
							'op_unit_price' => $product ['product_declared_value'],
							'op_subtotal' => round ( $product ['product_declared_value'] * $value->quantity, 2 ),
							'op_declared_value' => round ( $product ['product_declared_value'] * $value->quantity, 2 ),
							'op_weight' => round ( $product ['product_weight'] * $value->quantity, 2 ) 
					);
					$declaredValue += round ( $product ['product_declared_value'] * $value->quantity, 2 );
					$parcelContents .= $product ['product_title'] . ';	';
					$parcelQty += $value->quantity;
				} else {
					$result ['message'] = 'SKU can not be null.';
					return $result;
				}
				$key ++;
			}
		} elseif (count ( $orderDetail ) == 1) {
			if ($orderDetail->sku) {
				$product = $productObj->getProductBySku ( $orderDetail->sku );
				if (! $product) {
					$result ['message'] = 'SKU: ' . $orderDetail->sku . '  can not be found.';
					return $result;
				}
				$orderProduct [] = array (
						'product_id' => $product ['product_id'],
						'op_quantity' => $orderDetail->quantity,
						'product_sku' => $product ['product_sku'],
						'op_description' => $product ['product_title'],
						'op_unit_price' => $product ['product_declared_value'],
						'op_subtotal' => round ( $product ['product_declared_value'] * $orderDetail->quantity, 2 ),
						'op_declared_value' => round ( $product ['product_declared_value'] * $orderDetail->quantity, 2 ),
						'op_weight' => round ( $product ['product_weight'] * $orderDetail->quantity, 2 ) 
				);
				$declaredValue += round ( $product ['product_declared_value'] * $orderDetail->quantity, 2 );
				$parcelContents .= $product ['product_title'];
				$parcelQty += $orderDetail->quantity;
			} else {
				$result ['message'] = 'SKU can not be null.';
				return $result;
			}
		} else {
			$declaredValue = $orders->parcel_declared_value;
			$parcelContents = $orders->parcelContents;
			$parcelQty = $orders->parcel_quantity;
		}
		
		$orderInfo = array (
				'order_id' => $orders->order_id,
				'customer_id' => $this->_customerId,
				'consignee_address1' => $consigneeAddress1,
				'consignee_address2' => $consigneeAddress2,
				'consignee_city' => $consigneeCity,
				'consignee_company' => $consigneeCompany,
				'consignee_country_id' => $countryId,
				'consignee_email' => $consigneeEmail,
				'consignee_first_name' => $consigneeFirstName,
				'consignee_last_name' => $consigneeLastName,
				'consignee_phone' => $consigneePhone,
				// 'consignee_region' => $consignee_region,
				'consignee_zip' => $consigneeZip,
				'customer_order_code' => $referenceNo,
				'parcel_contents' => $parcelContents,
				'parcel_declared_value' => $declaredValue,
				'parcel_quantity' => $parcelQty,
				'remark' => $instructions,
				'shipping_method' => $shippingMethodCode,
				'order_product' => $orderProduct,
				'shipping_fee_estimate' => 0 
		);
		
		$result = Merchant_Service_OrderProccess::edit ( $orderInfo );
		$str = var_export ( $result, true );
		self::logError ( $str );
		$return ['message'] = $result ['list'] ['message'];
		if ($result ['ask'] == false) {
			
			return $return;
		}
		
		$return ['ask'] = 'Success.';
		
		return $return;
	}
	
	/*
	 * getOrderByCode
	 */
	public function getOrderByCode($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		$ordersCode = ( string ) $paramter->ordersCode;
		$detailLevel = ( string ) $paramter->detailLevel;
		$now = date ( 'Y-m-d H:i:s' );
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'data' => '',
				'time' => $now 
		);
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		
		if (! $ordersCode) {
			$result ['message'] = 'Order code can not be null.';
			return $result;
		}
		$orders = Merchant_Service_Orders::getByValue ( $ordersCode, $field = 'orders_code' );
		
		if (! $orders || empty ( $orders )) {
			$result ['message'] = 'Can not find this order. Order Code:' . $ordersCode;
			return $result;
		} elseif ($orders ['customer_id'] != $this->_customerId) {
			$result ['message'] = 'No permissions.';
			return $result;
		}
		$warehouse = Merchant_Service_Warehouse::getDetail ( $orders ['warehouse_id'] );
		if ($orders ['orders_status'] > 5) { // 订单已发出后
			$orderShip = Merchant_Service_OrderShip::getByValue ( $ordersCode, $field = 'orders_code' );
			$trackNumber = $orderShip ['tracking_number'];
			$refTrackNumber = '';
			if ($orderShip ['orders_code'] != $orderShip ['ref_tracking_number']) {
				$refTrackNumber = $orderShip ['ref_tracking_number'];
			}
			$carrierCode = $orderShip ['carrier_code'];
			$shippingFee = $orderShip ['os_shipping_fee'];
			$currencyCode = $orderShip ['currency_code'];
			$parcelWeight = $orderShip ['os_weight'];
		}
		$data = array (
				'ordersCode' => $orders ['orders_code'], // 订单编号
				'warehouse' => $warehouse ['warehouse_name'],
				'consigneeFirstName' => $orders ['consignee_first_name'],
				'consigneeLastName' => $orders ['consignee_last_name'],
				'consigneeCompany' => $orders ['consignee_company'],
				'consigneeZip' => $orders ['consignee_zip'],
				'consigneeRegion' => $orders ['consignee_region'],
				'consigneeCity' => $orders ['consignee_city'],
				'consigneeAddress1' => $orders ['consignee_address1'],
				'consigneeAddress2' => $orders ['consignee_address2'],
				'consigneePhone' => $orders ['consignee_phone'],
				'consigneeEmail' => $orders ['consignee_email'],
				'shippingMethod' => $orders ['shipping_method'],
				'parcelDeclaredValue' => $orders ['parcel_declared_value'],
				'parcelContents' => $orders ['parcel_contents'],
				'parcelQuantity' => $orders ['parcel_quantity'],
				'ordersStatus' => $orders ['orders_status'],
				'problemStatus' => $orders ['problem_status'],
				'shippingFeeEstimate' => $orders ['shipping_fee_estimate'],
				'referenceNo' => $orders ['customer_order_code'],
				'createTime' => $orders ['add_time'],
				
				'shipDate' => $orders ['ship_date'],
				'deliveredDate' => $orders ['delivered_date'],
				'trackingNumber' => $trackNumber,
				'refTrackingNumber' => $refTrackNumber,
				'carrierCode' => $carrierCode,
				'shippingFee' => $shippingFee,
				'currencyCode' => $currencyCode,
				'parcelWeight' => $parcelWeight 
		);
		
		if ($detailLevel == 1) {
			$condition ["orders_code"] = $orders ['orders_code'];
			$orderProduct = Merchant_Service_OrderProduct::getByCondition ( $condition );
			
			foreach ( $orderProduct as $val ) {
				$data ['orderProduct'] [] = array (
						
						'productSku' => $val ['product_sku'],
						'productTitle' => $val ['op_title'],
						'quantity' => $val ['op_quantity'],
						'weight' => $val ['weight'],
						'unitPrice' => $val ['op_unit_price'],
						'subtotal' => $val ['op_subtotal'],
						'declaredValue' => $val ['op_declared_value'],
						'categoryId' => $val ['op_category'] 
				);
			}
		}
		
		$result ['ask'] = 'Success';
		$result ['message'] = 'Success.';
		$result ['data'] = $data;
		return $result;
	}
	/*
	 * getOrderByCode
	 */
	public function getOrders($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		
		$now = date ( 'Y-m-d H:i:s' );
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'data' => '',
				'time' => $now 
		);
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		$condition = array ();
		
		if ($paramter->createTime->start)
			$condition ["add_time_start"] = $paramter->createTime->start;
		if ($paramter->createTime->end)
			$condition ["add_time_end"] = $paramter->createTime->end;
		
		if ($paramter->submitTime->start)
			$condition ['submit_time_start'] = $paramter->submitTime->start;
		if ($paramter->submitTime->start)
			$condition ['submit_time_end'] = $paramter->submitTime->end;
		
		if ($paramter->sentTime->start)
			$condition ['ship_date_start'] = $paramter->sentTime->start;
		if ($paramter->sentTime->start)
			$condition ['ship_date_end'] = $paramter->sentTime->end;
		
		if ($paramter->status)
			$condition ['orders_status'] = $paramter->status;
		if ($paramter->problemStatus)
			$condition ['problem_status'] = $paramter->problemStatus;
		
		if ($paramter->ordersCode)
			$condition ['orders_code'] = $paramter->ordersCode;
		if ($paramter->referenceNo)
			$condition ['customer_order_code'] = $paramter->referenceNo;
		if ($paramter->shippingMethod)
			$condition ['shipping_method'] = $paramter->shippingMethod;
		if ($paramter->destinationCountry) {
			$countryObj = new Default_Service_Country ();
			$countryId = $countryObj->getIdByName ( $paramter->destinationCountry );
			if (! $countryId) {
				$result ['message'] = 'Can not find this country.';
				return $result;
			}
			$condition ["consignee_country_id"] = $countryId;
		}
		$pageSize = $paramter->steps->pageSize;
		$page = $paramter->steps->page;
		
		if (empty ( $condition ) & $pageSize == null) {
			$pageSize = 100;
			$page = 1;
		}
		
		$condition ["customer_id"] = $this->_customerId;
		$detailLevel = $paramter->detailLevel;
		$orderList = Merchant_Service_Orders::getByCondition ( $condition, $type = '*', $page, $pageSize, 0 );
		
		if (! $orderList || empty ( $orderList )) {
			$result ['message'] = 'no data. ';
			return $result;
		}
		foreach ( $orderList as $key => $orders ) {
			
			$warehouse = Merchant_Service_Warehouse::getDetail ( $orders ['warehouse_id'] );
			
			if ($orders ['orders_status'] > 5) { // 订单已发出后
				$orderShip = Merchant_Service_OrderShip::getByValue ( $orders ['orders_code'], $field = 'orders_code' );
				$trackNumber = $orderShip ['tracking_number'];
				$refTrackNumber = '';
				if ($orderShip ['orders_code'] != $orderShip ['ref_tracking_number']) {
					$refTrackNumber = $orderShip ['ref_tracking_number'];
				}
				$carrierCode = $orderShip ['carrier_code'];
				$shippingFee = $orderShip ['os_shipping_fee'];
				$currencyCode = $orderShip ['currency_code'];
				$parcelWeight = $orderShip ['os_weight'];
			}
			$data [$key] = array (
					'ordersCode' => $orders ['orders_code'], // 订单编号
					'warehouse' => $warehouse ['warehouse_name'],
					'consigneeFirstName' => $orders ['consignee_first_name'],
					'consigneeLastName' => $orders ['consignee_last_name'],
					'consigneeCompany' => $orders ['consignee_company'],
					'consigneeZip' => $orders ['consignee_zip'],
					'consigneeRegion' => $orders ['consignee_region'],
					'consigneeCity' => $orders ['consignee_city'],
					'consigneeAddress1' => $orders ['consignee_address1'],
					'consigneeAddress2' => $orders ['consignee_address2'],
					'consigneePhone' => $orders ['consignee_phone'],
					'consigneeEmail' => $orders ['consignee_email'],
					'shippingMethod' => $orders ['shipping_method'],
					'parcelDeclaredValue' => $orders ['parcel_declared_value'],
					'parcelContents' => $orders ['parcel_contents'],
					'parcelQuantity' => $orders ['parcel_quantity'],
					'ordersStatus' => $orders ['orders_status'],
					'problemStatus' => $orders ['problem_status'],
					'shippingFeeEstimate' => $orders ['shipping_fee_estimate'],
					'referenceNo' => $orders ['customer_order_code'],
					'createTime' => $orders ['add_time'],
					
					'shipDate' => $orders ['ship_date'],
					'deliveredDate' => $orders ['delivered_date'],
					'trackingNumber' => $trackNumber,
					'refTrackingNumber' => $refTrackNumber,
					'carrierCode' => $carrierCode,
					'shippingFee' => $shippingFee,
					'currencyCode' => $currencyCode,
					'parcelWeight' => $parcelWeight 
			);
			
			if ($detailLevel == 1) {
				$condition ["orders_code"] = $orders ['orders_code'];
				$orderProduct = Merchant_Service_OrderProduct::getByCondition ( $condition );
				foreach ( $orderProduct as $val ) {
					$data [$key] ['orderProduct'] [] = array (
							
							'productSku' => $val ['product_sku'],
							'productTitle' => $val ['op_title'],
							'quantity' => $val ['op_quantity'],
							'weight' => $val ['weight'],
							'unitPrice' => $val ['op_unit_price'],
							'subtotal' => $val ['op_subtotal'],
							'declaredValue' => $val ['op_declared_value'],
							'categoryId' => $val ['op_category'] 
					);
				}
			}
		}
		
		$result ['ask'] = 'Success';
		$result ['message'] = 'Success.';
		$result ['data'] = $data;
		return $result;
	}
	
	/*
	 * updateOrderStatu
	 */
	public function updateOrderStatu($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		$now = date ( 'Y-m-d H:i:s' );
		$ordersCode = ( string ) $paramter->ordersCode;
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'ordersCode' => $ordersCode,
				'time' => $now 
		);
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		$statu = ( int ) $paramter->statu;
		// :0 删除,1 草稿,2 已确认,3 On Hold
		$statArr = array (
				0,
				1,
				2,
				3 
		);
		if (! in_array ( $statu, $statArr )) {
			$result ['message'] = 'Order statu is not allow. ';
			return $result;
		}
		
		if (! $ordersCode) {
			$result ['message'] = 'Order code can not be null.';
			return $result;
		}
		$orderObj = new Merchant_Service_OrderProccess ();
		
		$orderObj->setCustomer ( $this->_customerId );
		$return = $orderObj->submited ( $ordersCode, $statu, true, true ); // 强制扣款
		
		if ($return ['ask'] == 'Error') {
			
			$result ['message'] = $return ['msg'];
			return $result;
		}
		$result ['message'] = 'Success';
		$result ['ask'] = 'Success';
		return $result;
	}
	/*
	 * Authenticate
	 */
	private function authenticate() {
		$customerAuthObj = new Default_Model_CustomerAuthenticate ();
		$customerAuth = $customerAuthObj->getByValue ( $this->_customerId, 'customer_id' );
		
		if ($customerAuth ['ca_token'] == $this->_token & $customerAuth ['ca_key'] == $this->_key) {
			$this->_auth = true;
			return true;
		}
		$this->_error = 'App Token/App Key Not match for ' . $this->_customerId . '.';
		return false;
	}
	private function logError($error) {
		
		// $str = var_export($return,true);
		// self::logError($str);
		$logger = new Zend_Log ();
		$uploadDir = APPLICATION_PATH . "/../data/log/";
		$writer = new Zend_Log_Writer_Stream ( $uploadDir . 'api.log' );
		$logger->addWriter ( $writer );
		$logger->info ( date ( 'Y-m-d H:i:s' ) . ': ' . $error . " \n" );
	}
	
	/*
	 * StopOrder
	 */
	public function stopOrder($paramter) {
		$this->_customerId = ( string ) $paramter->HeaderRequest->customerId;
		$this->_token = ( string ) $paramter->HeaderRequest->appToken;
		$this->_key = ( string ) $paramter->HeaderRequest->appKey;
		$now = date ( 'Y-m-d H:i:s' );
		$ordersCode = ( string ) $paramter->ordersCode;
		$result = array (
				'ask' => 'Error',
				'message' => '',
				'ordersCode' => $ordersCode,
				'time' => $now 
		);
		$this->authenticate ();
		if (! $this->_auth) {
			$result ['message'] = $this->_error;
			return $result;
		}
		$return = Merchant_Service_Orders::stop ( $ordersCode, $this->_customerId );
		$result ['message'] = $return ['message'];
		if ($return ['ask'] == 'Error') {
			return $result;
		}
		$result ['ask'] = $return ['ask'];
		return $result;
	}
}